package com.practice.container;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.HashMap;


/**
 * 进行servlet容器进行模拟
 */
public class SimpleHttpServer {
    private static final int PORT = 8080;
    private static final HashMap<String, Handler> routes = new HashMap<>();

    public static void main(String[] args) throws IOException{
        //注册路由
        routes.put("/hello",new HelloHandler());

        try (ServerSocket serverSocket = new ServerSocket(PORT)){
            System.out.println("Server is running on http://localhost:" + PORT);

            while (true){
                Socket clientSocket =serverSocket.accept();
                System.out.println("Connected by " + clientSocket.getInetAddress());

                // 为每个客户端创建新线程
                new Thread(new ClientHandler(clientSocket)).start();
            }
        }
    }

    //客户端处理线程
    static class ClientHandler implements Runnable{
        private final Socket clientSocket;

        ClientHandler(Socket socket){
            this.clientSocket = socket;
        }

        @Override
        public void run() {
            try (BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
                 OutputStream out = clientSocket.getOutputStream()){
                //解析路径请求
                String path = parseRequest(in);
                Handler handler = routes.getOrDefault(path,new NotFoundHandler());

                //生成并发送响应
                String response = handler.handle();
                out.write(response.getBytes());
                out.flush();
            } catch (IOException e) {
                System.err.println("Error handling client: " + e.getMessage());
            }finally {
                try {
                    clientSocket.close();
                }catch (IOException e){
                    System.err.println("Error closing socket: " + e.getMessage());
                }
            }
        }

        private String parseRequest(BufferedReader in) throws IOException {
            String requestLine = in.readLine();
            if(requestLine!=null){
                String[] parts = requestLine.split(" ");
                if(parts.length >= 2){
                    return parts[1];
                }
            }
            return "";
        }
    }


}
